package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;

/**
 * Phpwind论坛
 * @author Chase
 *
 */
public class PhpwindBbsAnalyse implements AnalyseNews {
//http://bbs.0757qq.com/read-htm-tid-185736.html
	private static final String[] regex = {
		"http://www.phpwind.net/read/[0-9]+"
	};


	
	public boolean isDetailPage(String url) {
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta meta = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String url = urlMeta.getUrl();
		/*
		 * 网站源码
		 */
		String htmltxt = urlMeta.getHtml();
		String title = null;
		String content = null;
		String author = null;
		Long date = null;
		Document doc = Jsoup.parse(htmltxt);

		/*
		 * 标题
		 */
		title = doc.select("h1#J_post_title").text();

		Element firstDiV = doc.select("div[id^=read_]").first();
		if(firstDiV!=null){
			Element first = firstDiV.select("div.name").first();
			if(first!=null) author = first.text();
			date = DateUtils.matchDate(firstDiV.select("div.floor_top_tips").text());
			content = HtmlCleaner.getContentHtml(url,  firstDiV.select("div.editor_content"));
		}

		/*
		 * 链接
		 */
		meta.setUrl(url);

		/*
		 * 来源
		 */
		meta.setTitle(title);
		meta.setContent(content);
		meta.setAuthor(author);
		meta.setDate(date);


		/**
		 * 评论数  点击数
		 */
		Integer clickNum=null;
		Integer commnetNum=null;
		if (clickNum == null && commnetNum==null ){
			String commTxt = doc.select("div.post_num").text();
			commnetNum = NumberUtils.matchNumber(StringUtils.substringBefore(commTxt, "回复"));
			clickNum = NumberUtils.matchNumber(StringUtils.substringAfter(commTxt, "回复"));
		}

		meta.setClickNum(clickNum);
		meta.setCommentNum(commnetNum);
		meta.setUpdateUrl(url);

		return meta;
	}

	

	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if(StringUtils.isNotBlank(updateUrl)){
				UrlMeta urlMeta  = CrawlHTML.responseToURL(updateUrl);
				return parserHtml(urlMeta);
			}
		}
		return null;
	}


	
}
